package com.pucheng.bracelet.viewmodel

import android.content.Context
import androidx.lifecycle.MutableLiveData
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.clj.fastble.exception.BleException
import com.clj.fastble.utils.HexUtil
import com.pucheng.bracelet.app.ble.*
import com.pucheng.bracelet.app.util.CacheUtil
import me.hgj.jetpackmvvm.base.viewmodel.BaseViewModel
import no.nordicsemi.android.dfu.DfuProgressListener
import java.io.File
import kotlin.random.Random

/**
 * @author liwei
 * @date 2/21/21
 * @email liwei254610320@163.com
 */
class UpgradeViewModel : BaseViewModel() {
    private var data = Random(5).nextBoolean()
    val version = MutableLiveData<String>().apply {
        value = "MY-78-2.2.2"
    }
    val versionTips = MutableLiveData<String>().apply {
        value = if (data) "更新到最新版本" else "已经是最新固件"

    }
    val newFirmware = MutableLiveData<Boolean>().apply {
        value = data
    }

    fun upgrade(context: Context) {
        ToastUtils.showShort("正在升级手环固件")
        //开始正式升级
//        val filePath: String =
//            context.getExternalFilesDir(null)!!.path + File.separator + "RES_V1.4.bin"
//        ClientManager.getInstance().upData(filePath,object : BleWriteAndNotifyCallback() {
//            override fun onWriteSuccess(
//                current: Int,
//                total: Int,
//                justWrite: ByteArray?
//            ) {
////                    getServiceleepData(bleDevice)
//            }
//
//            override fun onWriteFailure(exception: BleException?) {
//            }
//
//            override fun onCharacteristicChanged(data: ByteArray?) {
////                LogUtils.e("资 = :${HexUtil.encodeHexStr(data)}")
//
//            }
//        })
        ClientManager.getInstance().sendCmd(BleUUId.UUID_3802,
            BleUUId.UUID_5A00, BleCmd.OPEN_FOTA, object : BleWriteAndNotifyCallback() {
                override fun onWriteSuccess(
                    current: Int,
                    total: Int,
                    justWrite: ByteArray?
                ) {
//                    getServiceleepData(bleDevice)
                    startDfu(context)
                }

                override fun onWriteFailure(exception: BleException?) {
                }

                override fun onCharacteristicChanged(data: ByteArray?) {
                    LogUtils.e("FOTa = :${HexUtil.encodeHexStr(data)}")
                }
            })
    }

    private fun startDfu(context: Context) {
        //先注册进度以及升级状态回调
        DfuUtils.getInstance().setmDfuProgressListener(context, object : DfuProgressListener {
            override fun onDeviceConnecting(deviceAddress: String) {}
            override fun onDeviceConnected(deviceAddress: String) {}
            override fun onDfuProcessStarting(deviceAddress: String) {
                newFirmware.value = true
            }
            override fun onDfuProcessStarted(deviceAddress: String) {}
            override fun onEnablingDfuMode(deviceAddress: String) {}
            override fun onProgressChanged(
                deviceAddress: String,
                percent: Int,
                speed: Float,
                avgSpeed: Float,
                currentPart: Int,
                partsTotal: Int
            ) {
                LogUtils.e("dfu更新进度：$percent")
                LogUtils.e("dfu更新速度：$speed")
            }

            override fun onFirmwareValidating(deviceAddress: String) {}
            override fun onDeviceDisconnecting(deviceAddress: String) {}
            override fun onDeviceDisconnected(deviceAddress: String) {}
            override fun onDfuCompleted(deviceAddress: String) {
                newFirmware.value = false
                versionTips.value = "更新完成"
            }
            override fun onDfuAborted(deviceAddress: String) {
                //升级流产，失败
                newFirmware.value = false
                versionTips.value = "更新失败"
            }
            override fun onError(
                deviceAddress: String,
                error: Int,
                errorType: Int,
                message: String
            ) {
                //升级错误
                newFirmware.value =false
                versionTips.value = "更新失败：$message"
            }
        });//升级状态回调
        //开始正式升级
        val filePath: String =
            context.getExternalFilesDir(null)!!.path + File.separator + "app_dfu_package_MF_V2_5.zip"
        LogUtils.e("dfu$filePath")
        val watchBean = CacheUtil.getWatchInfo()
        DfuUtils.getInstance().startUpdate(context, watchBean!!.mac, watchBean!!.name, filePath)
    }
}